<?php
/**
 * Created by PhpStorm.
 * User: wq
 * Date: 2021/5/10
 * Time: 13:41
 */

namespace App\Utils;


use OSS\OssClient;
use OSS\Core\OssException;

class OSS
{
    protected $accessKeyId;
    protected $accessKeySecret;
    protected $endpoint;
    protected $bucket;


    public function __construct()
    {
        $this->accessKeyId = env('OSS_ACCESS_KEY');
        $this->accessKeySecret = env('OSS_ACCESS_SECRET');
        $this->endpoint=env('OSS_ENDPOINT');
        // 存储空间名称
        $this->bucket= env('OSS_BUCKET');
        // <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg
        $this->file_name= "shop/";
    }

    /**
     * 删除文件
     * @param $file_name
     * @throws ApiException
     */
    public  function delFile($file_name)
    {
        try{
            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
            $ossClient->deleteObject($this->bucket, $file_name);
        } catch(OssException $e) {
            throwError($e->getMessage());
            throw new ApiException($e->getMessage());
        }

    }

    /**
     * 添加文件
     * @param $file
     * @param string $fileName
     * @return string
     * @throws ApiException
     */
    public function addFile($file,$fileName = '')
    {
        $object = $this->file_name.$fileName. "." . $file->getClientOriginalExtension();
        $filePath = $file;
        try {
            $oss = new OssClient($this->accessKeyId, $this->accessKeySecret,$this->endpoint);
            $oss->uploadFile($this->bucket, $object, $filePath);
        } catch (OssException $e) {
            throwError($e->getMessage());
        }
        return $object;
    }

    public function addLocalFile($file,$fileName)
    {
        $fileName =  $this->file_name.$fileName;
        try {
            $oss = new OssClient($this->accessKeyId, $this->accessKeySecret,$this->endpoint);
            $oss->uploadFile($this->bucket, $fileName,$file);
        } catch (OssException $e) {
            throwError($e->getMessage());
        }
        return $fileName;
    }

}
